package org.tao.lightningmq.nameserver.handler;


import com.alibaba.fastjson2.JSON;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.tao.lightningmq.common.enums.NameServerEventCode;
import org.tao.lightningmq.common.event.EventBus;
import org.tao.lightningmq.common.event.model.BaseEvent;
import org.tao.lightningmq.common.tcp.TcpMsg;
import org.tao.lightningmq.nameserver.event.model.NodeReplicationAckMsgEvent;

/**
 * @Author lht
 * @date 2025/1/17 - 14:42
 * @description:
 */
@ChannelHandler.Sharable
public class NodeSendReplicationMsgServerHandler extends SimpleChannelInboundHandler<TcpMsg> {

    private EventBus eventBus;

    public NodeSendReplicationMsgServerHandler(EventBus eventBus) {
        this.eventBus = eventBus;
        eventBus.init();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TcpMsg tcpMsg) throws Exception {
        int code = tcpMsg.getCode();
        byte[] body = tcpMsg.getBody();
        BaseEvent event = null;
        if (NameServerEventCode.NODE_REPLICATION_ACK_MSG.getCode() == code) {
            event = JSON.parseObject(body, NodeReplicationAckMsgEvent.class);
        }
        event.setContext(channelHandlerContext);
        eventBus.publish(event);
    }
}
